export default {
  namespaced: true,
  
  state: () => ({
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  mutations: {
    // 商品加入购物车
    addToCart(state, goods) {
      const findResult = state.cart.find(item => item.goods_id === goods.goods_id)
      if(!findResult) {
        state.cart.push(goods)
      } else {
        findResult.goods_count++
      }
      this.commit('moduleCart/saveToStorage')
    },
    saveToStorage(state) {
      uni.setStorageSync('cart', JSON.stringify(state.cart))
    },
    // 更新商品的状态
    updateGoodsState(state, goods) {
      state.cart.forEach(item => item.goods_state = item.goods_id === goods.goods_id? goods.goods_state : item.goods_state)
      
      // 更新本地的数据
      this.commit('moduleCart/saveToStorage')
    },
    updateGoodsCount(state, goods) {
      state.cart.forEach(item => {
        if(item.goods_id === goods.goods_id) {
          item.goods_count = goods.goods_count
        }
      })
      
      // 更新本地数据
      this.commit('moduleCart/saveToStorage')
    },
    removeGoodsById(state, goods_id) {
      state.cart = state.cart.filter(item => item.goods_id !== goods_id)
      
      // 更新本地数据
      this.commit('moduleCart/saveToStorage')
    },
    // 该百年所有商品的状态
    changeAllState(state, newState) {
      // 点击全选后将所有商品的状态改为全选状态的反状态
      state.cart.forEach(item => item.goods_state = newState)
      
      // 更新本地数据
      this.commit('moduleCart/saveToStorage') 
    }
  },
  getters: {
    // 商品详情页中购物车商品的总数
    total(state) {
      return state.cart.reduce((prev, curr) => prev += curr.goods_count, 0)
    },
    // 购物车中选中商品的总数
    checkedCount(state) {
      // 首先筛选出选中的商品数
      const checkedArr = state.cart.filter(item => item.goods_state === true)
      return checkedArr.reduce((prev, curr) => prev += curr.goods_count, 0)
    },  
    // 选中商品的总价
    checkedTotalPrice(state) {
      return state.cart.reduce((prev, curr) => 
        curr.goods_state? (prev + curr.goods_count * curr.goods_price) : prev
      , 0)
    },
    // 是否全选
    isAllChecked(state) {
      return state.cart.every(item => item.goods_state === true)
    }
  }
}